package com.medistat.dialog.services;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.medistat.model.Doctor;
import com.medistat.model.Work;
import com.medistat.model.enums.TypeOfWork;
import com.medistat.persistance.service.interfaces.PersistanceService;
import com.medistat.util.DateUtils;

@Service("dutiesProvider")
public class DutiesProviderImpl implements DutiesProvider {
	
	private PersistanceService persistanceService;

	@Autowired
	public void setPersistanceService(PersistanceService persistanceService) {
		this.persistanceService = persistanceService;
	}
	
	@Override
	public Map<String, Integer> getAllDutiesForAllDoctorsInMonth(Integer year, Integer month) throws Exception {
		List<Work> works =persistanceService.getDutiesForMonth(year, month);
		Map<Long, Integer> map = initializeDutiesForDoctor();
		filterOutWeekendDuties(works, map);
		return convertToFormatForGui(map);
	}
	
	@Override
	public Map<String, Integer> getAllDutiesForAllDoctorsInYear(Integer year) throws Exception {
		Map<Long, Integer> map = getAllDutiesForAllDoctorsFor(year);
		return convertToFormatForGui(map);
	}

	private void filterOutWeekendDuties(List<Work> works, Map<Long, Integer> map) {
		if(works==null) {
			return;
		}
		for (Work work : works) {
			if(work==null) {
				continue;
			}
			if (TypeOfWork.DUTY.equals(work.getTypeOfWork()) && DateUtils.isWeekend(work.getDay())) {
				Doctor doctor = work.getDoctor();
				if (doctor == null) {
					continue;
				}
				Integer numberOfDuties = map.get(doctor.getId());
				map.put(doctor.getId(), numberOfDuties + 1);
			}
		}
	}

	private Map<String, Integer> convertToFormatForGui(Map<Long, Integer> map) throws Exception {
		Map<String, Integer> result = new HashMap<String, Integer>();
		for(Map.Entry<Long, Integer> entry : map.entrySet()) {
			Doctor doctor = persistanceService.getDoctor(entry.getKey());
			result.put(doctor.getName() + " " + doctor.getSurname(), entry.getValue());
		}
		return result;
	}
	
	
	private Map<Long, Integer> getAllDutiesForAllDoctorsFor(Integer year) {
		Map<Long, Integer> map = initializeDutiesForDoctor();
		List<Work> duties = persistanceService.getDutiesForYear(year);
		if (duties == null || duties.isEmpty()) {
			return map;
		}
		filterOutWeekendDuties(duties, map);
		
		return map;
	}
	
	private Map<Long, Integer> initializeDutiesForDoctor() {
		Map<Long, Integer> map = new HashMap<Long, Integer>();
		List<Doctor> doctors = persistanceService.getAll(Doctor.class);
		for (Doctor doctor : doctors) {
			map.put(doctor.getId(), Integer.valueOf(0));
		}
		return map;
	}
}
